import { getToken } from '@/utils/cookie'
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  //导航守卫，全局守卫(相当于拦截器，路由跳转之前，给他进行逻辑的操作)
  routes: [
    {
      path: '/oj/login',
      name: 'login',
      component: () => import('@/views/Login.vue'),
    } ,
    {
      path: '/',
      redirect:"/oj/login"
    }                          //..表示上一级,层级比较多就要写很多的..不美观
    ,{
      path: '/oj/layout',
      name: 'layout',
      component: () => import('@/views/Layout.vue'),
      children:[
        {
          path: 'question',
          name: 'question',
          component: () => import('@/views/Question.vue'),
        },
        {
          path: 'exam',
          name: 'exam',
          component: () => import('@/views/Exam.vue'),
        }, {
          path: 'updateExam',
          name: 'updateExam',
          component: () => import('@/views/UpdateExam.vue'),
        },
        {
          path: 'cuser',
          name: 'cuser',
          component: () => import('@/views/Cuser.vue'),
        }
      ]
    },    
  ]
})

router.beforeEach((to,from,next) => {
  if(getToken()){
    /* has token 那么就去直接跳转*/
    if(to.path=='/oj/login'){
      next({path: '/oj/layout/question'})
    }else{
      next()
    }       
   }else{       //否则恢复登录
    if(to.path!=='/oj/login'){
      next({
        path:'/oj/login'
      })
    }else{
      next()
    }
   }
  })

export default router
